package com.mos.iot.mqtt.listener.converter.impl;

import cn.hutool.core.util.ClassUtil;
import com.mos.iot.mqtt.listener.MqttTopicMessage;
import com.mos.iot.mqtt.listener.converter.MessageConverter;
import org.eclipse.paho.client.mqttv3.MqttMessage;

public class TopicMessageConverter implements MessageConverter {
    @Override
    public <T> T convert(Object value, Class<T> target, T defaultValue) throws IllegalArgumentException {
        if(value != null) {
            if (target.isAssignableFrom(MqttTopicMessage.class) && !ClassUtil.isBasicType(value.getClass())) {
                if (value instanceof MqttMessage) {
                    MqttMessage message = (MqttMessage) value;
                    String content = new String(message.getPayload());
                    return (T) MqttTopicMessage.builder().payload(content).build();
                }
            }
        }
        return defaultValue;
    }
}
